package cn.broadsense.common.jackson;

import cn.broadsense.common.annotation.SM4Decode;
import cn.broadsense.common.utils.Sm4SecurityUtil;
import cn.broadsense.common.utils.spring.SpringUtils;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;

import java.io.IOException;
import java.util.Objects;

/**
 * @author: pengxin
 * @create: 2024-07-26 14:53
 * @Version 1.0
 **/
@Slf4j
public class SM4Serialize extends JsonSerializer<String> implements ContextualSerializer {

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        try {
            if (SpringUtils.isProd()){
                String decrypt = Sm4SecurityUtil.decrypt(value);
                gen.writeString(decrypt);
            }else{
                gen.writeString(value);
            }

        } catch (BeansException e) {
            log.error("解密失败 => {}", e.getMessage());
            gen.writeString(value);
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        SM4Decode annotation = property.getAnnotation(SM4Decode.class);
        if (Objects.nonNull(annotation) && Objects.equals(String.class, property.getType().getRawClass())) {
            return this;
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}
